package form

import (
	"errors"
	"github.com/gin-gonic/gin"
	"yak.admin/src/entity"
	"yak.admin/src/module/backend/admin/repository"
	"yak.admin/src/util"
)

type AdminForm struct {
	Username string `form:"Data[username]" validate:"required,max=36" chn:"用户名"`
	Nickname string `form:"Data[nickname]" validate:"required,max=36" chn:"昵称"`
	Type     int    `form:"Data[type]" validate:"required" chn:"类型"`
	Province string `form:"Data[province]"`
	City     string `form:"Data[city]"`
	County   string `form:"Data[county]"`
	Address string
	Group int
}

func (form *AdminForm) Valid() error {
	if form.Group != entity.AdminSuper {
		var address string
		regionRepository := repository.AdminRepository{}
		if province, exist := regionRepository.FindOneById(form.Province); exist {
			address += province.Name
		} else {
			return errors.New("省份信息设置失败")
		}

		if city, exist := regionRepository.FindOneByIdAndParentId(form.City, form.Province); exist {
			address += city.Name
		} else {
			return errors.New("市信息设置失败")
		}

		if county, exist := regionRepository.FindOneByIdAndParentId(form.County, form.City); exist {
			address += county.Name
		}
		form.Address = address
	}
	return nil
}

func (form *AdminForm) CreateSuper(c *gin.Context) (entity.Admin, error) {
	if err := util.DefaultGetValidParams(c, form); err != nil {
		return entity.Admin{}, err
	}
	admin := entity.Admin{
		Group:    form.Group,
		Username: form.Username,
		Nickname: form.Nickname,
		Type:     form.Type,
	}
	db := util.GetMysqlPool().Handler()
	if db.Create(&admin).NewRecord(admin) {
		return admin, errors.New("创建失败")
	}
	return admin, nil
}

func (form *AdminForm) CreateNormal(c *gin.Context, t int) (entity.Admin, error) {
	if err := util.DefaultGetValidParams(c, form); err != nil {
		return entity.Admin{}, err
	}
	admin := entity.Admin{
		Group: form.Group,
		Username: form.Username,
		Nickname: form.Nickname,
		Type: t,
		Province: form.Province,
		City:     form.City,
		County:   form.County,
		Address: form.Address,
	}
	db := util.GetMysqlPool().Handler()
	if db.Create(&admin).NewRecord(admin) {
		return admin, errors.New("创建失败")
	}
	return admin, nil
}

func ResetDefaultPassword(c *gin.Context, id int) error {
	db := util.GetMysqlPool().Handler()
	password := util.GetSystemValue("default_password")
	var admin entity.Admin
	if rows := db.Model(&admin).Where("id = ?", id).Update("password", admin.GetPassword(password)).RowsAffected; rows > 0 {
		return nil
	}
	return errors.New("更新失败")
}

func DeleteAdmin(c *gin.Context, id int) error {
	db := util.GetMysqlPool().Handler()
	if rows := db.Delete(entity.Admin{}, "id = ?", id).RowsAffected; rows > 0 {
		return nil
	}
	return errors.New("删除失败")
}
